package com.bk.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import com.bk.service.SsoFeign;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**
 * @author czl Zuul过滤器，实现了路由检查
 */
public class AccessFilter extends ZuulFilter {

	public static final String ERROR_TYPE = "error";
	public static final String POST_TYPE = "post";
	public static final String PRE_TYPE = "pre";
	public static final String ROUTE_TYPE = "route";

	@Autowired
	private SsoFeign ssoFeign;

	/**
	 * 通过int值来定义过滤器的执行顺序
	 */
	@Override
	public int filterOrder() {
		return 0;
	}

	/**
	 * 过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型： public static final String ERROR_TYPE =
	 * "error"; public static final String POST_TYPE = "post"; public static final
	 * String PRE_TYPE = "pre"; public static final String ROUTE_TYPE = "route";
	 */
	@Override
	public String filterType() {
		return PRE_TYPE;
	}

	/**
	 * 过滤器的具体逻辑
	 */
	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		HttpServletResponse response = ctx.getResponse();

        if (request.getMethod().equals("OPTIONS")) {
            return false;
        }
		// 访问路径
		String url = request.getRequestURL().toString();
		String token=request.getHeader("Authorization");
		// 过滤规则：cookie有令牌且存在于Redis，或者访问的是登录页面、登录请求则放行
		if (url.contains("bk-employee/ssoLogin") || url.contains("bk-role/getAllRoleList")
				|| (!StringUtils.isEmpty(token) && token!="undefined"/*|| ssoFeign.hasKey(token)*/)) {
			ctx.setSendZuulResponse(true);
			ctx.setResponseStatusCode(200);
			return null;
		}else {
			ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            ctx.setResponseBody("{\"status\":401,\"msg\":\"user is not login !\"}");
            ctx.getResponse().setContentType("text/html;charset=UTF-8");
			// 重定向到登录页面
//			try {
//				response.sendRedirect("http://localhost");
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
			return null;
		}
	}

	/**
	 * 返回一个boolean类型来判断该过滤器是否要执行
	 */
	@Override
	public boolean shouldFilter() {
		 RequestContext ctx = RequestContext.getCurrentContext();
	        HttpServletRequest request = ctx.getRequest();
	        //只过滤OPTIONS 请求
	        if(request.getMethod().equals(RequestMethod.OPTIONS.name())){
	            return true;
	        }

	        return false;
	}
}